<template>
  <view class="secondhand-publish-page">
    <view class="form-container">
      <!-- 标题 -->
      <view class="form-section">
        <view class="form-item">
          <view class="form-label">标题</view>
          <view class="form-input-wrapper">
            <input 
              class="form-input" 
              type="text" 
              placeholder="请填写" 
              v-model="formData.intro"
              maxlength="50"
            />
          </view>
        </view>
      </view>

      <!-- 商品分类 -->
      <view class="form-section">
        <view class="form-item clickable" @click="openCategoryPicker">
          <view class="form-label">商品分类</view>
          <view class="form-value-wrapper">
            <text class="form-value">{{ categoryLabel }}</text>
            <text class="iconfont icon-ic_rightarrow arrow-icon"></text>
          </view>
        </view>
      </view>

      <!-- 产品类型 -->
      <view class="form-section">
        <view class="form-item clickable" @click="openProductCatePicker">
          <view class="form-label">产品类型</view>
          <view class="form-value-wrapper">
            <text class="form-value">{{ productCateLabel }}</text>
            <text class="iconfont icon-ic_rightarrow arrow-icon"></text>
          </view>
        </view>
      </view>

      <!-- 商品描述 -->
      <view class="form-section">
        <view class="form-item description-item">
          <view class="form-label">商品描述</view>
          <view class="textarea-wrapper">
            <textarea 
              class="form-textarea" 
              placeholder="描述商品的品牌型号、功能成色、出手原因..."
              v-model="formData.content"
              maxlength="1000"
            />
          </view>
        </view>
      </view>

      <!-- 商品图片上传 -->
      <view class="form-section">
        <view class="form-item">
          <view class="image-upload-section">
            <view class="image-list">
              <view 
                class="upload-placeholder" 
                v-if="formData.images.length < 9"
                @click="uploadImage"
              >
                <text class="upload-icon">+</text>
              </view>
              <view 
                class="image-item" 
                v-for="(image, index) in formData.images" 
                :key="index"
              >
                <image class="uploaded-image" :src="image" mode="aspectFill" />
                <view class="delete-btn" @click.stop="deleteImage(index)">
                  <text class="iconfont icon-ic_close"></text>
                </view>
              </view>
              
            </view>
          </view>
        </view>
      </view>

      <!-- 价格 -->
      <view class="form-section">
        <view class="form-item">
          <view class="form-label">价格</view>
          <view class="form-input-wrapper">
            <input 
              class="form-input" 
              type="digit" 
              placeholder="请填写" 
              v-model="formData.price"
            />
          </view>
        </view>
      </view>

      <!-- 发货方式 -->
      <view class="form-section">
        <view class="form-item clickable" @click="openDeliveryPicker">
          <view class="form-label">发货方式</view>
          <view class="form-value-wrapper">
            <text class="form-value">{{ formData.deliveryMethod || '不限' }}</text>
            <text class="iconfont icon-ic_rightarrow arrow-icon"></text>
          </view>
        </view>
      </view>

      <!-- 地址选择 -->
      <view class="form-section">
        <view class="form-item clickable" @click="selectAddress">
          <view class="address-info">
            <text class="iconfont icon-ic_location1 location-icon"></text>
            <text class="address-text">{{ formData.address || '选择地址' }}</text>
          </view>
          <text class="iconfont icon-ic_rightarrow arrow-icon"></text>
        </view>
      </view>
    </view>

    <!-- 底部发布按钮 -->
    <view class="bottom-action-bar">
      <button class="publish-btn" @click="publishProduct">确认发布</button>
    </view>

    <!-- 发货方式选择器 -->
    <u-picker 
      :show="showDeliveryPicker" 
      :columns="deliveryColumns" 
      keyName="label"
      @confirm="confirmDelivery"
      @cancel="showDeliveryPicker = false"
    ></u-picker>

    <u-picker 
      :show="showCategoryPicker"
      :columns="categoryColumns"
      keyName="label"
      @confirm="confirmCategory"
      @cancel="showCategoryPicker = false"
    ></u-picker>

    <u-picker 
      :show="showProductCatePicker"
      :columns="productCateColumns"
      keyName="label"
      @confirm="confirmProductCate"
      @cancel="showProductCatePicker = false"
    ></u-picker>
  </view>
</template>

<script>
import { merchantProductSave, getMerCategoryListApi, getMerchantProductCateTreeApi } from '@/api/merchant.js';

const deliveryMethodMap = {
  '快递配送': '1',
  '到店自提': '2',
  '同城配送': '3',
  '当面交易': '4'
};

export default {
  data() {
    return {
      formData: {
        intro: '',
        content: '',
        images: [],
        price: '',
        categoryId: null,
        cateId: null,
        deliveryMethod: '不限',
        address: '华润万象华府3栋'
      },
      showDeliveryPicker: false,
      showCategoryPicker: false,
      showProductCatePicker: false,
      deliveryOptions: [
        { label: '不限', value: '不限' },
        { label: '快递配送', value: '快递配送' },
        { label: '到店自提', value: '到店自提' },
        { label: '同城配送', value: '同城配送' },
        { label: '当面交易', value: '当面交易' }
      ],
      categoryOptions: [],
      productCateOptions: []
    }
  },
  computed: {
    deliveryColumns() {
      return [this.deliveryOptions];
    },
    categoryColumns() {
      return [this.categoryOptions];
    },
    categoryLabel() {
      const current = this.categoryOptions.find(item => item.value === this.formData.categoryId);
      return current ? current.label : '请选择';
    },
    productCateColumns() {
      return [this.productCateOptions];
    },
    productCateLabel() {
      const current = this.productCateOptions.find(item => item.value === this.formData.cateId);
      return current ? current.label : '请选择';
    }
  },
  created() {
    this.fetchCategoryOptions();
    this.fetchProductCateOptions();
  },
  methods: {
    // 上传图片
    uploadImage() {
      const maxCount = 9 - this.formData.images.length;
      uni.chooseImage({
        count: maxCount,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePaths = res.tempFilePaths;
          // 这里应该上传到服务器，暂时使用本地路径
          this.formData.images = this.formData.images.concat(tempFilePaths);
          console.log('选择的图片:', tempFilePaths);
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 删除图片
    deleteImage(index) {
      this.formData.images.splice(index, 1);
    },
    
    // 打开发货方式选择器
    openDeliveryPicker() {
      this.showDeliveryPicker = true;
    },
    
    // 确认发货方式选择
    confirmDelivery(e) {
      const idx = (e.indexs && e.indexs[0]) || 0;
      const item = this.deliveryOptions[idx];
      if (item) {
        this.formData.deliveryMethod = item.value;
      }
      this.showDeliveryPicker = false;
    },

    // 打开分类选择
    openCategoryPicker() {
      if (!this.categoryOptions.length) {
        this.fetchCategoryOptions();
      }
      this.showCategoryPicker = true;
    },

    // 分类选择确认
    confirmCategory(e) {
      const idx = (e.indexs && e.indexs[0]) || 0;
      const option = this.categoryOptions[idx];
      if (option) {
        this.formData.categoryId = option.value;
      }
      this.showCategoryPicker = false;
    },

    // 获取分类数据
    async fetchCategoryOptions() {
      try {
        const res = await getMerCategoryListApi();
        const list = Array.isArray(res.data) ? res.data : [];
        this.categoryOptions = list.map(item => ({
          label: item.categoryName || item.name || '未命名分类',
          value: item.categoryId || item.id
        })).filter(option => option.value);
      } catch (error) {
        console.error('获取商品分类失败:', error);
        uni.showToast({
          title: '加载分类失败',
          icon: 'none'
        });
      }
    },

    // 打开产品类型选择器
    openProductCatePicker() {
      if (!this.productCateOptions.length) {
        this.fetchProductCateOptions();
      }
      this.showProductCatePicker = true;
    },

    // 产品类型确认
    confirmProductCate(e) {
      const idx = (e.indexs && e.indexs[0]) || 0;
      const option = this.productCateOptions[idx];
      if (option) {
        this.formData.cateId = option.value;
      }
      this.showProductCatePicker = false;
    },

    // 获取产品类型数据
    async fetchProductCateOptions() {
      try {
        const res = await getMerchantProductCateTreeApi();
        const list = Array.isArray(res.data) ? res.data : [];
        const flatList = [];
        const traverse = (nodes = []) => {
          nodes.forEach(node => {
            if (node) {
              flatList.push({
                label: node.name || node.title || '未命名类型',
                value: node.id || node.categoryId
              });
              if (Array.isArray(node.children) && node.children.length) {
                traverse(node.children);
              }
            }
          });
        };
        traverse(list);
        this.productCateOptions = flatList.filter(option => option.value);
      } catch (error) {
        console.error('获取产品类型失败:', error);
      }
    },
    
    // 选择地址
    selectAddress() {
      // 跳转到地址选择页面或使用地图选择
      uni.chooseLocation({
        success: (res) => {
          this.formData.address = res.name || res.address || '华润万象华府3栋';
          console.log('选择的地址:', res);
        },
        fail: (err) => {
          console.error('选择地址失败:', err);
          // 如果选择失败，可以跳转到地址列表页面
          uni.navigateTo({
            url: '/pages/fast/my-address-list',
            success: (res) => {
              console.log('跳转到地址列表');
            },
            fail: (err) => {
              console.error('跳转失败:', err);
            }
          });
        }
      });
    },
    
    // 验证表单
    validateForm() {
      if (!this.formData.intro.trim()) {
        uni.showToast({
          title: '请输入标题',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.content.trim()) {
        uni.showToast({
          title: '请输入商品描述',
          icon: 'none'
        });
        return false;
      }
      
      if (this.formData.images.length === 0) {
        uni.showToast({
          title: '请上传商品图片',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.price || parseFloat(this.formData.price) <= 0) {
        uni.showToast({
          title: '请输入有效的价格',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.address) {
        uni.showToast({
          title: '请选择地址',
          icon: 'none'
        });
        return false;
      }

      if (!this.formData.categoryId) {
        uni.showToast({
          title: '请选择商品分类',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.cateId) {
        uni.showToast({
          title: '请选择产品类型',
          icon: 'none'
        });
        return false;
      }
      
      return true;
    },
    
    // 发布商品
    async publishProduct() {
      if (!this.validateForm()) {
        return;
      }
      
      const payload = this.buildSubmitPayload();
      
      uni.showLoading({
        title: '发布中...'
      });
      
      try {
        await merchantProductSave(payload);
        uni.hideLoading();
        uni.showToast({
          title: '发布成功！',
          icon: 'success',
          duration: 2000
        });
        
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } catch (error) {
        uni.hideLoading();
        console.error('发布商品失败:', error);
        uni.showToast({
          title: (error && error.message) || error || '发布失败，请重试',
          icon: 'none'
        });
      }
    },
    
    // 构造提交数据
    buildSubmitPayload() {
      const images = this.formData.images || [];
      const description = (this.formData.content || '').trim();
      const title = (this.formData.intro || '').trim();
      const payload = {
        name: title,
        intro: description.slice(0, 60),
        content: description,
        image: images[0] || '',
        sliderImage: images.join(','),
        keyword: title,
        address: this.formData.address || '',
        price: this.formData.price ? Number(this.formData.price) : undefined,
        categoryId: this.formData.categoryId,
        cateId: this.formData.cateId,
        deliveryMethod: deliveryMethodMap[this.formData.deliveryMethod] || '',
        specType: false,
        isSub: false,
        isAutoUp: false,
        isAutoSubmitAudit: false,
        refundSwitch: true
      };
      
      Object.keys(payload).forEach(key => {
        if (payload[key] === '' || payload[key] === undefined) {
          delete payload[key];
        }
      });
      
      return payload;
    }
  }
}
</script>

<style lang="scss" scoped>
.secondhand-publish-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 160rpx;
}

.form-container {
  width: 680rpx;
  padding: 30rpx;
  margin: 20rpx auto;
  border-radius: 20rpx;
  background: #fff;

}
.form-label {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  flex-shrink: 0;
  width: fit-content !important;
  margin-right: 20rpx;
}
.form-section {
  background: white;
  margin-bottom: 10rpx;
  border-bottom: 1rpx solid #dddddd;
  &:last-child {
    border-bottom: none;
  }
  
  
  .form-item {
    padding: 40rpx 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    
    &.clickable {
      cursor: pointer;
    }
    
    &.description-item {
      align-items: flex-start;
      flex-direction: column;
      
      .form-label {
        margin-bottom: 20rpx;
      }
    }
    

    
    .form-input-wrapper {
      flex: 1;
      display: flex;
      justify-content: flex-end;
    }
    
    .form-input {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      padding: 0 24rpx;
      height: 80rpx;
      border: none;
      background: #f8f9fa;
      border-radius: 12rpx;
      text-align: left;
      
      &::placeholder {
        color: #999;
      }
    }
    
    .textarea-wrapper {
      width: 100%;
      margin-top: 20rpx;
    }
    
    .form-textarea {
      width: 100%;
      min-height: 300rpx;
      font-size: 28rpx;
      color: #333;
      padding: 0;
      border: none;
      background: transparent;
      text-align: left;
      line-height: 1.6;
      
      &::placeholder {
        color: #999;
      }
    }
    
    .form-value-wrapper {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      
      .form-value {
        font-size: 28rpx;
        color: #333;
        margin-right: 16rpx;
      }
      
      .arrow-icon {
        font-size: 28rpx;
        color: #999;
      }
    }
    
    .address-info {
      flex: 1;
      display: flex;
      align-items: center;
      
      .location-icon {
        font-size: 32rpx;
        color: #ED6567;
        margin-right: 12rpx;
      }
      
      .address-text {
        font-size: 28rpx;
        color: #333;
      }
    }
    
    .arrow-icon {
      font-size: 28rpx;
      color: #999;
      margin-left: 16rpx;
    }
  }
}

// 图片上传区域
.image-upload-section {
  width: 100%;
  margin-top: 20rpx;
  
  .image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    
    .image-item {
      position: relative;
      width: 180rpx;
      height: 180rpx;
      border-radius: 12rpx;
      overflow: hidden;
      
      .uploaded-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .delete-btn {
        position: absolute;
        top: 8rpx;
        right: 8rpx;
        width: 48rpx;
        height: 48rpx;
        background: rgba(0, 0, 0, 0.6);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .iconfont {
          font-size: 24rpx;
          color: white;
        }
      }
    }
    
    .upload-placeholder {
      width: 180rpx;
      height: 180rpx;
      background: #f8f9fa;
      border: 2rpx dashed #ddd;
      border-radius: 12rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      
      .upload-icon {
        font-size: 100rpx;
        color: #999;
        font-weight: 300;
        line-height: 1;
      }
    }
  }
}

// 底部操作栏
.bottom-action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  // background: white;
  padding: 30rpx 40rpx;
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
  // box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.1);
  z-index: 100;
  
  .publish-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background: #ED6567;
    color: white;
    border: none;
    border-radius: 50rpx;
    font-size: 32rpx;
    font-weight: 600;
  }
}
</style>

